package com.lkc.util;

import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.codec.Base64;
import lombok.Data;

import java.util.Map;
import java.util.UUID;

@Data
public class CaptchaUtil {
    private static final ExpiryMap expiryMap = new ExpiryMap();
    private static final long EXPIRY_TIME = 1000 * 60 * 8;

    // 添加静态方法获取 expiryMap 实例
    public static ExpiryMap getExpiryMap() {
        return expiryMap;
    }

    //获取验证码
    public static Map getCaptcha() {
        //定义图形验证码的长和宽
        CircleCaptcha captcha = cn.hutool.captcha.CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        //图片
        String imgbase64 = Base64.encode(captcha.getImageBytes());
        System.out.println(imgbase64);
        //验证码中的编号
        String code = captcha.getCode();
        System.out.println(code);
        String key = UUID.randomUUID().toString();
        Map map = Map.of("key", key, "base", "data:image/png;base64," + imgbase64);
        expiryMap.put(key, code, EXPIRY_TIME);
        return map;
    }

    //验证码校验
    public static boolean checkCaptcha(String key, String code) {
        String captchaCode = (String) expiryMap.get(key);
        return code.equalsIgnoreCase(captchaCode);
    }
}
